package com.company.nuwa.common.utils;

import com.company.nuwa.common.enumration.SignType;
import org.springframework.util.ObjectUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * <p>签名工具类</p>
 *
 * @author yangmingkai
 * @version 1.0
 * @date 2020/09/18 13:59
 **/
public class SignUtils {

    /**
     * 校验签名验证
     * @param map 参数
     * @return
     */
    public static boolean checkSign(Map<String, String> map,String key,String signature) throws Exception{
        if(ObjectUtils.isEmpty(signature)){
            return false;
        }
        // 签名
        // 开始验证签名
        String sign = generateSignature(map, key);
        if (signature.equals(sign)) {
            // 签名正确
            return true;
        }
        return false;
    }


    /**
     * 校验签名验证
     * @param map 参数
     * @return
     */
    public static boolean checkSign(Map<String, String> map,String key) throws Exception{
        // 签名
        String wxSign = map.get("sign");
        map.remove("sign");
        try {
            // 开始验证签名
            String sign = generateSignature(map, key);
            if (wxSign.equals(sign)) {
                // 签名正确
                return true;
            }
        } catch (Exception e) {
            throw e;
        }
        return false;
    }


    /**
     * 生成签名
     *
     * @param data 待签名数据
     * @param key API密钥
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        return generateSignature(data, key, SignType.MD5);
    }

    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data 待签名数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key, SignType signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals("sign") ){
                continue;
            }
            // 参数值为空，则不参与签名
            if (data.get(k).trim().length() > 0)
            {
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
            }

        }
        sb.append("key=").append(key);
        if (SignType.MD5.equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        }
        else if (SignType.HMACSHA256.equals(signType)) {
            return HMACSHA256(sb.toString(), key);
        }
        else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }

    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 生成 HMACSHA256
     * @param data 待处理数据
     * @param key 密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }
}
